// pages/middlePage/middlePage.js
import * as API_Stroe from '../../api/store'
import * as API_Member from '../../api/member'
import * as API_Config from '../../api/sysConfig'
import * as API_Upload from '../../utils/fileUpload'
import {
  staffLoginByUserPwd
} from '../../api/fix'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    default_avatar: '',
    member: {},
    // showBtn:false,
    // enableAccountLogin:'N'
    showBtn: true,
    enableAccountLogin: 'Y',
    staffshow: false,
    phone: '',
    password: ''
  },
  staffLogin() {
    this.setData({
      staffshow: !this.data.staffshow
    })
  },
  spacefn() {},
  inputPhone(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  inputPwd(e) {
    this.setData({
      password: e.detail.value
    })
  },
  staffloginSubmit() {
    console.log('login')
    // this.setHeadImg(1)
    // return
    const data = {
      phone: this.data.phone,
      password: this.data.password,
      userType: 2
    }
    staffLoginByUserPwd(data).then(({
      data,
      code,
      msg
    }) => {
      // console.log(data)
      if (code === 200) {
        wx.setStorageSync('token', data.token)
        wx.setStorageSync('member', data.member)
        wx.setStorageSync('store', data)
        wx.setStorageSync('storeId', data.id)
        wx.setStorageSync('loginType', 2)
        if (!data.member.headImg) {
          this.setHeadImg(data.member.id)
        }
        this.setData({
          store: data
        })
        wx.navigateTo({
          url: '/pages/sstaffIndex/staffIndex',
        })
      } else {
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
      
    })
  },
  setHeadImg (id) {
    const base64 = this.data.default_avatar
    const time = new Date().getTime();
    const imgPath = wx.env.USER_DATA_PATH + "/poster" + time + "share" + ".png";
    //如果图片字符串不含要清空的前缀,可以不执行下行代码.
    const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
    const fs = wx.getFileSystemManager();
    fs.writeFileSync(imgPath, imageData, "base64");
    fs.close()
    API_Upload.upload(imgPath, res => {
      let requestData = JSON.parse(res.data)
      if (requestData.code !== 200) {
        return
      }
      const { url } = requestData
      const data = {
        headImg: url,
        id: id
      }
      API_Member.updateMember(data).then(res => {
        if (res.code === 200) {
          let store = wx.getStorageSync('store')
          store.member.headImg = url
          wx.setStorageSync('member', store.member)
          wx.setStorageSync('store', store)
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // wx.removeStorageSync('store');
    // wx.removeStorageSync('storeId');
    wx.showLoading({
      title: '加载中',
    })
    const member = wx.getStorageSync('member')
    const token = wx.getStorageSync('token')
    const openId = getApp().globalData.openId || wx.getStorageSync('openid')
    const loginType = wx.getStorageSync('loginType')
    let url = loginType === 1 ? '/pages/home/home' : '/pages/sstaffIndex/staffIndex'
    if (member && token && openId) {
      wx.hideLoading()
      if (loginType === 1) {
        wx.switchTab({
          url: url,
        })
      }
      if (loginType === 2) {
        wx.redirectTo({
          url: url,
        })
      }
    } else {
      wx.hideLoading()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    // this.getStoreInfo();
    this.flushMember();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.flushLogin();
    // let that = this
    // API_Config.getValueByKey("enableAccountLogin").then(res => {
    //   if ('Y' == res) {
    //     //允许员工登录
    //     that.setData({
    //       enableAccountLogin: res
    //     })
    //   }
    // })
  },
  flushMember: function () {
    const member = wx.getStorageSync('member');
    this.setData({
      member: member
    });
  },
  getStoreInfo: function () {
    let that = this
    API_Stroe.getStroe().then(res => {
      console.log(res);
      if (res) {
        //有门店，先进门店
        if (res.code === 200) {
          wx.setStorageSync('store', res.data)
          wx.setStorageSync('storeId', res.data.id)

          wx.setStorageSync('loginType', 1)
          that.setData({
            store: res.data
          })
          wx.switchTab({
            url: '../home/home',
          })
        }
        if (res.code === 500) {
          wx.showToast({
            title: res.msg || '获取门店信息失败',
            icon: 'none'
          })
        }
      } else {
        //没找到门店，看还有没有申请中的门店
        that.toApply();

      }
    })
  },
  toApply: function () {
    let that = this;
    API_Stroe.getApply().then(res => {
      if (res) {
        //有在申请中的，
        wx.redirectTo({
          url: '../storeApplyResult/storeApplyResult',
        })
      } else {
        //申请中的也没有，显示按钮
        that.setData({
          showBtn: true
        });
        //完全没有
        // wx.navigateTo({
        //   url: '../storeApply/storeApply',
        // })
      }
    })
  },
  toApplyUrl: function () {
    wx.navigateTo({
      url: '../storeApply/storeApply',
    })
  },
  flushLogin: function () {
    //因为这个code只能用一次，使用一次后需要刷新下
    let that = this;
    wx.login({
      timeout: 8000,
      success(res) {
        that.setData({
          wxlogincode: res.code
        });

      }
    })
  },
  getPhone: function (e) {
    let that = this;
    if (!e.detail.iv) {
      //认为用户拒绝了或者关闭了授权 
      wx.showToast({
        title: '为了获取您的员工信息，请同意授权手机号',
        icon: 'none'
      })
      return;
    }
    const params = {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      code: this.data.wxlogincode
    }
    API_Member.flushPhone(params).then(res => {
      console.log(res);
      if (res.code == 200) {
        let data = res.data;
        wx.setStorageSync('token', data.token)
        wx.setStorageSync('member', data.member)
        that.getStoreInfo()
        that.flushMember();
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
      that.flushLogin();
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


})